﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;

namespace CancelBOSSOrder
{
    public class ParseLogFile
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void GetBOSSOrders()
        {
            TruncateBossSyncTable();

            using (var sr = new StreamReader(ConfigurationManager.AppSettings["syncfile"], Encoding.Default))
            {
                while (sr.Peek() >= 0)
                {
                    var bossOrderID = sr.ReadLine().Trim();
                    if (!bossOrderID.StartsWith("="))
                    {
                        InsertIntoBossSyncTable(bossOrderID);
                    }                    
                }
            }

            CheckNotExistOrders();
            CheckCancelFailureOrdersBeforeVersion2();
            CheckCancelFailureOrders();
        }

        /// <summary>
        /// 清空同步表
        /// </summary>
        private static void TruncateBossSyncTable()
        {
            const string sql = "truncate table Tempdb.dbo.BOSSOrderSync";

            var sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            var sqlcmd = new SqlCommand();
            sqlcmd.Connection = sqlconn;
            sqlcmd.CommandText = sql;

            try
            {
                sqlcmd.Connection.Open();
                sqlcmd.ExecuteNonQuery();
            }
            finally
            {
                sqlcmd.Connection.Close();
            }

        }

        /// <summary>
        /// 将待处理的预订单导入同步表
        /// </summary>
        /// <param name="bossOrderID"></param>
        private static void InsertIntoBossSyncTable(string bossOrderID)
        {
            const string sql = "insert into Tempdb.dbo.BOSSOrderSync (bossOrderID) values (@bossOrderID)";

            var sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            var sqlcmd = new SqlCommand();
            sqlcmd.Connection = sqlconn;
            sqlcmd.CommandText = sql;

            sqlcmd.Parameters.Add("@bossOrderID", SqlDbType.NVarChar, 64);
            sqlcmd.Parameters["@bossOrderID"].Value = bossOrderID;

            try
            {
                sqlcmd.Connection.Open();
                sqlcmd.ExecuteNonQuery();
            }
            finally
            {
                sqlcmd.Connection.Close();
            }
        }

        private static void CheckNotExistOrders()
        {
            const string sql = @"select distinct BOSSOrderID from tempdb.dbo.bossordersync
                                except 
                                select bossorderid from ecsscoredb.dbo.orderbossincome
                                order by bossorderid";

            var sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            var sqlcmd = new SqlCommand();
            sqlcmd.Connection = sqlconn;
            sqlcmd.CommandText = sql;


            try
            {
                sqlcmd.Connection.Open();
                var sqlrd = sqlcmd.ExecuteReader();

                while(sqlrd.Read())
                {
                    CancelBOSSOrderID(sqlrd["BOSSOrderID"].ToString());
                }
            }
            finally
            {
                sqlcmd.Connection.Close();
            }
        }

        private static void CheckCancelFailureOrdersBeforeVersion2()
        {
            const string sql = @"select distinct BOSSOrderID from tempdb.dbo.bossordersync
                                intersect 
                                select a.bossorderid from ecsscoredb.dbo.orderbossincome a
                                join (select * from  ecsscoredb.dbo.orderinfo where orderstatus
                                in (2,8,10)) b
                                on a.orderid=b.orderid";

            var sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            var sqlcmd = new SqlCommand();
            sqlcmd.Connection = sqlconn;
            sqlcmd.CommandText = sql;


            try
            {
                sqlcmd.Connection.Open();
                var sqlrd = sqlcmd.ExecuteReader();

                while (sqlrd.Read())
                {
                    CancelBOSSOrderID(sqlrd["BOSSOrderID"].ToString());
                }
            }
            finally
            {
                sqlcmd.Connection.Close();
            }
        }

        private static void CheckCancelFailureOrders()
        {
            const string sql = @"select distinct BOSSOrderID from tempdb.dbo.bossordersync
                                intersect 
                                select a.bossorderid from ecsscoredb.dbo.orderbossincome a
                                join (select * from  ecsscoredb.dbo.orderinfo where orderstatus
                                in (2,8,10)) b
                                on a.orderid=b.orderid";

            var sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            var sqlcmd = new SqlCommand();
            sqlcmd.Connection = sqlconn;
            sqlcmd.CommandText = sql;


            try
            {
                sqlcmd.Connection.Open();
                var sqlrd = sqlcmd.ExecuteReader();

                while (sqlrd.Read())
                {
                    CancelBOSSOrderID(sqlrd["BOSSOrderID"].ToString());
                }
            }
            finally
            {
                sqlcmd.Connection.Close();
            }
        }


        private static void CancelBOSSOrderID(string bossOrderID)
        {
            try
            {
                var wcf = new BOSSInterfaceInvoke();

                ResBOSSInvokeEntityOfstring result = wcf.BOSSOrderCancel(bossOrderID);

                if (result.Succeedk__BackingField)
                {
                    AddSyncLog(bossOrderID, 0, result.Messagek__BackingField);
                }
                else
                {
                    AddSyncLog(bossOrderID, 1, result.Messagek__BackingField);
                }
            }
            catch (Exception ex)
            {
                log.Error("取消BOSS预定单过程出现异常", ex);
            }
        }

        private static void AddSyncLog(string bossOrderID,int result,string remark)
        {
            const string sql = "insert into OrderBOSSOrderSync (BOSSOrderID,Result,Remark) values (@BOSSOrderID,@Result,@Remark)";


            var sqlconn = new SqlConnection();
            sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["ECSSDb"].ConnectionString;

            var sqlcmd = new SqlCommand();
            sqlcmd.Connection = sqlconn;
            sqlcmd.CommandText = sql;

            sqlcmd.Parameters.Add("@BOSSOrderID", SqlDbType.NVarChar, 64);
            sqlcmd.Parameters["@BOSSOrderID"].Value = bossOrderID;

            sqlcmd.Parameters.Add("@Result", SqlDbType.TinyInt);
            sqlcmd.Parameters["@Result"].Value = result;

            sqlcmd.Parameters.Add("@Remark", SqlDbType.NVarChar,1024);
            sqlcmd.Parameters["@Remark"].Value = remark;


            try
            {
                sqlcmd.Connection.Open();

                sqlcmd.ExecuteNonQuery();
            }
            finally
            {
                sqlcmd.Connection.Close();
            }
        }
    }
}
